package services

import (
	"encoding/json"
	"errors"
	"net/url"
	"weiboxs.com/new_h_glasses/models"
)

type EquipmentService struct {
}

// 保存数据
func (s *EquipmentService) Eqsavedata(archives_id int64, tdata string, start int64, end int64, admin models.BackendUser) error {
	archives, err := models.GetArchivesById(archives_id)
	if err != nil {
		return err
	}
	if archives.Id == 0 {
		return errors.New("找不到档案信息")
	}
	data, err := url.QueryUnescape(tdata)
	if err != nil {
		return err
	}
	//用户资料添加完成，开始处理检查数据
	eq_data, _ := models.GetEquipmentDataByScreeningId(archives.Id, start, end)
	new_eq_data := new(models.EquipmentData)
	if err := json.Unmarshal([]byte(data), new_eq_data); err != nil {
		return errors.New("检查数据解析失败：" + err.Error())
	}
	if eq_data.Id == 0 { //新增
		new_eq_data.Archives = archives
		if _, err := new_eq_data.Insert(); err != nil {
			return errors.New("检查数据保存失败：" + err.Error())
		}
	} else { //修改
		eq_data.RightVision = s.check_eq_is_my(new_eq_data.RightVision, eq_data.RightVision)
		eq_data.LeftVision = s.check_eq_is_my(new_eq_data.LeftVision, eq_data.LeftVision)
		eq_data.RightCorrectVision = s.check_eq_is_my(new_eq_data.RightCorrectVision, eq_data.RightCorrectVision)
		eq_data.LeftCorrectVision = s.check_eq_is_my(new_eq_data.LeftCorrectVision, eq_data.LeftCorrectVision)

		eq_data.RightPressure = s.check_eq_is_my(new_eq_data.RightPressure, eq_data.RightPressure)
		eq_data.LeftPressure = s.check_eq_is_my(new_eq_data.LeftPressure, eq_data.LeftPressure)
		eq_data.LeftBallDiameter = s.check_eq_is_my(new_eq_data.LeftBallDiameter, eq_data.LeftBallDiameter)
		eq_data.RightBallDiameter = s.check_eq_is_my(new_eq_data.RightBallDiameter, eq_data.RightBallDiameter)
		eq_data.LeftColumnDiameter = s.check_eq_is_my(new_eq_data.LeftColumnDiameter, eq_data.LeftColumnDiameter)
		eq_data.RightColumnDiameter = s.check_eq_is_my(new_eq_data.RightColumnDiameter, eq_data.RightColumnDiameter)
		eq_data.LeftAxial = s.check_eq_is_my(new_eq_data.LeftAxial, eq_data.LeftAxial)
		eq_data.RightAxial = s.check_eq_is_my(new_eq_data.RightAxial, eq_data.RightAxial)
		eq_data.EyeLeftAxial = s.check_eq_is_my(new_eq_data.EyeLeftAxial, eq_data.EyeLeftAxial)
		eq_data.EyeRightAxial = s.check_eq_is_my(new_eq_data.EyeRightAxial, eq_data.EyeRightAxial)

		err := eq_data.Update("RightVision", "LeftVision",
			"RightCorrectVision", "LeftCorrectVision",
			"LeftBallDiameter", "RightBallDiameter",
			"LeftColumnDiameter", "RightColumnDiameter",
			"LeftAxial", "RightAxial",
			"RightPressure", "LeftPressure",
			"EquipmentYg", "EquipmentYy",
			"EyeLeftAxial", "EyeRightAxial",
			"UpdatedAt")
		if err != nil {
			return errors.New("检查数据更新失败：" + err.Error())
		}

	}
	return nil
}

// 验证是否需要等于自己
func (s *EquipmentService) check_eq_is_my(new, old string) string {
	if len(new) == 0 {
		return old
	}
	return new
}
